import tkinter as tk
from tkinter import ttk
from typing import Literal, Optional
from pyopencl_z.ui.util import rgb_dec2hex


class TableLine(ttk.Frame):
    name_width: int = 10
    max_text_width: int = 25

    def __init__(self,
                 master=None,
                 name: str = 'name',
                 text: str = 'text',
                 width: int = 50,
                 pad_y: int = 3,
                 **kwargs,
                 ) -> None:
        super().__init__(master, width=width, **kwargs)

        self.name_width = min(TableLine.name_width, int(width * 0.5))
        self.text_label_pad_x = 2
        self.pad_y = pad_y

        text_width = width - self.name_width - self.text_label_pad_x
        self.text_width = min(TableLine.max_text_width, text_width)

        self.name_label = ttk.Label(
            self, text=name, anchor='ne', width=self.name_width,
            foreground=rgb_dec2hex(50, 50, 50))
        self.text_label = ttk.Label(
            self, text=text, anchor='n', relief=tk.GROOVE, borderwidth=1, width=self.text_width,
            foreground=rgb_dec2hex(53, 53, 200))

    def pack(self, side: Literal['top', 'left', 'right', 'bottom'] = 'top', **kwargs) -> None:
        self.name_label.pack(side='left', pady=self.pad_y)
        self.text_label.pack(side='left', pady=self.pad_y, padx=self.text_label_pad_x)

        super().pack(side=side, **kwargs)


class TableFrame(ttk.LabelFrame):
    def __init__(self,
                 master=None,
                 title: str = '',
                 width: int = 100,
                 height: int = 100,
                 **kwargs,
                 ) -> None:
        self.label = ttk.Label(master, text=title, foreground=rgb_dec2hex(50, 50, 50))
        super().__init__(master, labelwidget=self.label, width=width, height=height, **kwargs)

        self.width = width
        self.height = height
        self.table_lines = []

    def add_line(self, name: str, text: str) -> None:
        width = int(self.width * 0.9)
        self.table_lines.append(TableLine(self, name=name, text=text, width=width))

    def pack(self, **kwargs) -> None:
        for frame in self.table_lines:
            frame.pack()

        super().pack(**kwargs)


if __name__ == '__main__':
    root = tk.Tk()

    a = TableFrame(root, width=300, height=200, title='123')
    a.add_line('device', '123')
    a.pack()

    root.mainloop()
